package com.cml.rpc.serialize;

import com.cml.rpc.common.RpcRequest;
import com.cml.rpc.common.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author cml
 * @create 2021/7/21 17:01
 */
public class Encode extends MessageToByteEncoder {
    private Serialize serialize;

    public Encode(Serialize serialize) {
        this.serialize = serialize;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf byteBuf) throws Exception {
        System.out.println(msg.getClass());
        // 写入消息类型
        if (msg instanceof RpcRequest) {
            byteBuf.writeShort(MessageType.Request.getCode());
        } else if (msg instanceof RpcResponse) {
            byteBuf.writeShort(MessageType.Response.getCode());
        }
        byteBuf.writeShort(serialize.getType());
        byte[] bytes = this.serialize.serialize(msg);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
    }
}
